#include<iostream>
#include<mysql/mysql.h>
#include<string>
#include<unistd.h>
using namespace std;

const string host="127.0.0.1";
const string user="Workbench";
const string password="123456";
const string db="For_CPP_study";
const unsigned int port = 3306;


int main()
{
    cout<<"mysql client version: "<<mysql_get_client_info()<<endl;
    //句柄
    MYSQL* my=mysql_init(nullptr);
    if(my==nullptr)
    {
        cerr<<"init mysql error"<<endl;
        return 1;
    }

    if(mysql_real_connect(my,host.c_str(),user.c_str(),password.c_str(),
        db.c_str(),port,nullptr,0)==nullptr)
    {
        cerr<<"connect error"<<endl;
        return 2;
    }
    mysql_set_character_set(my,"utf8");
    cout<<"connect success"<<endl;
    
    //string sql="insert into user (name,age,telphone) values ('Tom',12,'12734588')";
    //string sql="insert into user (name,age,telphone) values ('李四',13,'69834588')";
    string sql="select image_url from food";
    int n=mysql_query(my,sql.c_str());


    //和结果集有关的，获取具体元素
    MYSQL_RES* res=mysql_store_result(my);
    if(nullptr==res)
    {
        cerr<<"转储失败"<<endl;
    }
    int rows= mysql_num_rows(res);//行
    int fields=mysql_num_fields(res);//列

   //获取列名
    MYSQL_FIELD *fields_array=mysql_fetch_fields(res);
    for(int i= 0 ; i<fields;i++)
    {
        cout<<fields_array[i].name<<"\t";
    }
    cout<<endl;
    //具体数值

    for(int i = 0 ; i < rows ; i++)
    {
        MYSQL_ROW row=mysql_fetch_row(res);//拿到每一行的其实地址
        for(int j = 0 ; j < fields ; j++ )
        {
            cout << row[j] << "\t";//相当于解引用，*(row+j)
            cout << " ";
        fflush(stdout);
        }
        cout<<"\n";
         // 刷新输出缓冲区
    }
    cout << "\n";
    fflush(stdout);
     // 刷新输出缓冲区

    //释放结果集
    mysql_free_result(res);
    mysql_close(my); 
    return 0;
}